import pygame
import os
import math

class SoundManager:
    def __init__(self):
        self.sounds = {}
        self.music_volume = 0.5
        self.sound_volume = 0.7
        self.enabled = True
        
        # 初始化音效
        self._load_sounds()

    def _load_sounds(self):
        """加载音效文件"""
        sound_dir = os.path.join(os.path.dirname(__file__), '..', 'assets', 'sounds')
        
        # 确保音效目录存在
        os.makedirs(sound_dir, exist_ok=True)
        
        # 定义音效文件名和对应的键
        sound_files = {
            'launch': 'sling.wav',
            'collision': 'collision.wav',
            'break': 'break.wav',
            'victory': 'victory.wav',
            'bird': 'bird.wav'
        }
        
        # 创建默认音效
        self._create_default_sounds(sound_dir, sound_files)
        
        # 加载音效
        for key, filename in sound_files.items():
            path = os.path.join(sound_dir, filename)
            try:
                self.sounds[key] = pygame.mixer.Sound(path)
                self.sounds[key].set_volume(self.sound_volume)
            except pygame.error:
                print(f"Warning: Could not load sound {filename}")

    def _create_default_sounds(self, sound_dir, sound_files):
        """创建默认的音效文件（如果不存在）"""
        for sound_name, filename in sound_files.items():
            path = os.path.join(sound_dir, filename)
            if not os.path.exists(path):
                self._create_simple_sound_file(path)

    def _create_simple_sound_file(self, path):
        """创建一个简单的WAV音效文件"""
        import wave
        import struct
        
        # 创建一个简单的哔声音效
        duration = 0.1  # 秒
        frequency = 440  # Hz
        sample_rate = 44100
        amplitude = 32767
        num_samples = int(duration * sample_rate)
        
        with wave.open(path, 'w') as wav_file:
            # 设置参数
            wav_file.setnchannels(1)  # 单声道
            wav_file.setsampwidth(2)  # 2字节
            wav_file.setframerate(sample_rate)
            
            # 生成简单的正弦波
            for i in range(num_samples):
                t = float(i) / sample_rate
                value = int(amplitude * math.sin(2 * math.pi * frequency * t))
                data = struct.pack('<h', value)
                wav_file.writeframes(data)

    def play(self, sound_name):
        """播放指定音效"""
        if not self.enabled:
            return
            
        if sound_name in self.sounds:
            self.sounds[sound_name].play()

    def set_sound_volume(self, volume):
        """设置音效音量"""
        self.sound_volume = max(0.0, min(1.0, volume))
        for sound in self.sounds.values():
            sound.set_volume(self.sound_volume)

    def toggle_sound(self):
        """切换音效开关"""
        self.enabled = not self.enabled
        if not self.enabled:
            pygame.mixer.stop()